import React, { useEffect, useState } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import styles from './Deposit.module.css'
import axios from '../../axios'

export default function DepositResult() {
  const navigate = useNavigate()
  const location = useLocation()
  const [loading, setLoading] = useState(true)
  const [paymentStatus, setPaymentStatus] = useState(null)
  const [paymentAmount, setPaymentAmount] = useState(0)
  const [orderId, setOrderId] = useState('')

  useEffect(() => {
    // 从URL参数获取订单信息
    const query = new URLSearchParams(location.search)
    const outTradeNo = query.get('out_trade_no')
    
    if (outTradeNo) {
      setOrderId(outTradeNo)
      queryPaymentResult(outTradeNo)
    } else {
      setLoading(false)
      setPaymentStatus('failed')
    }
  }, [location])

  // 查询支付结果
  const queryPaymentResult = async (orderNo) => {
    try {
      setLoading(true)
      const response = await axios.get(`/api/alipay/query?orderId=${orderNo}`)
      
      if (response.data.code === 200) {
        const result = response.data.data
        // 检查支付状态
        if (result && result.alipay_trade_query_response) {
          const tradeStatus = result.alipay_trade_query_response.trade_status
          const amount = result.alipay_trade_query_response.total_amount || '0'
          
          setPaymentAmount(parseFloat(amount))
          
          if (tradeStatus === 'TRADE_SUCCESS' || tradeStatus === 'TRADE_FINISHED') {
            setPaymentStatus('success')
          } else if (tradeStatus === 'WAIT_BUYER_PAY') {
            setPaymentStatus('pending')
          } else {
            setPaymentStatus('failed')
          }
        } else {
          setPaymentStatus('failed')
        }
      } else {
        setPaymentStatus('failed')
      }
    } catch (error) {
      console.error('查询支付结果失败', error)
      setPaymentStatus('failed')
    } finally {
      setLoading(false)
    }
  }

  const handleRetry = () => {
    navigate('/my/deposit')
  }

  const handleBackToHome = () => {
    navigate('/my')
  }

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <div className={styles.backButton} onClick={() => navigate(-1)}>
          
        </div>
        <h1 className={styles.title}>支付结果</h1>
        <div className={styles.spacer}></div>
      </div>

      <div className={styles.card}>
        <div className={styles.resultContainer}>
          {loading ? (
            <div className={styles.resultDesc}>正在查询支付结果...</div>
          ) : (
            <>
              <div className={`${styles.resultIcon} ${paymentStatus === 'success' ? styles.resultSuccess : styles.resultFailed}`}>
                {paymentStatus === 'success' ? '✓' : paymentStatus === 'pending' ? '⏳' : '✗'}
              </div>
              
              <div className={styles.resultTitle}>
                {paymentStatus === 'success' 
                  ? '支付成功' 
                  : paymentStatus === 'pending' 
                    ? '等待支付' 
                    : '支付失败'}
              </div>
              
              <div className={styles.resultDesc}>
                {paymentStatus === 'success' 
                  ? '您的洋币已经成功充值到账户' 
                  : paymentStatus === 'pending' 
                    ? '订单已创建，等待支付完成' 
                    : '支付未完成，请重新尝试'}
              </div>

              {paymentStatus === 'success' && (
                <div className={styles.resultAmount}>
                  <div className={styles.resultAmountLabel}>已充值金额</div>
                  <div className={styles.resultAmountValue}>
                    {paymentAmount} 元 = {paymentAmount * 10} 洋币
                  </div>
                </div>
              )}

              <div className={styles.resultButtons}>
                {paymentStatus === 'success' ? (
                  <button 
                    className={`${styles.resultButton} ${styles.primaryButton}`}
                    onClick={handleBackToHome}
                  >
                    返回我的
                  </button>
                ) : (
                  <>
                    <button 
                      className={`${styles.resultButton} ${styles.secondaryButton}`}
                      onClick={handleBackToHome}
                    >
                      返回我的
                    </button>
                    <button 
                      className={`${styles.resultButton} ${styles.primaryButton}`}
                      onClick={handleRetry}
                    >
                      重新充值
                    </button>
                  </>
                )}
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  )
} 